package com.zhss.microservice.server.node.ha;

import com.zhss.microservice.server.node.network.ServerNetworkManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * candidate节点重连线程
 */
public class CandidateReconnectThread extends Thread {

    private static final Logger LOGGER = LoggerFactory.getLogger(CandidateReconnectThread.class);
    private static final long CANDIDATE_RECONNECT_INTERVAL = 60 * 1000;

    private Integer candidateNodeId;
    private String candidateAddress;

    public CandidateReconnectThread(Integer candidateNodeId,
                                    String candidateAddress) {
        this.candidateNodeId = candidateNodeId;
        this.candidateAddress = candidateAddress;
    }

    @Override
    public void run() {
        // 每隔一段时间，尝试对失联的比自己nodeid小的candidate发起重连请求
        while(true) {
            try {
                Thread.sleep(CANDIDATE_RECONNECT_INTERVAL);
                ServerNetworkManager serverNetworkManager = ServerNetworkManager.getInstance();
                boolean isConnected = serverNetworkManager.connectServerNode(candidateAddress);
                if(isConnected) {
                    break;
                }
            } catch(Exception e) {
                LOGGER.error(e.getMessage());
            }
        }
    }

}
